package popmail
{
	import mx.utils.Base64Encoder;

	public class EMLparser extends Object
	{
		import mx.utils.Base64Decoder;
		import mx.utils.StringUtil;
		import util.StringHelper;
		import util.DecodeMimeHeader;
		
		public var date:String = "";
		public var subject:String = "";
		public var from:String = "";
		public var reply:String = "";
		public var to:String = "";
		public var cc:String = "";
		public var fromName:String = "";
		private var dec:Base64Decoder = new Base64Decoder;
		
		public function EMLparser($value:Object)
		{
			EMLtoOBJECT($value);
		}
		
		private function EMLtoOBJECT($value:Object):void
		{
			var str:String = $value.toString();
			var arr:Array = $value as Array;
			var relCheck:String = "";
			for(var i:int = 0; i < arr.length ; i++)
			{
				//trace(line);
				
				var line:String = arr[i];
				//trace("line ==>",line);
				if(line == "")
					continue;
				else if(relCheck != "" && line.indexOf("=?") == 0)
				{
					this[relCheck] += decodeString(line);
				}
				else if(date == "" && line.indexOf("Date:") == 0)
				{
					relCheck = "date";
					date = decodeString(line.substring(5));
				}
				else if(from == "" && line.indexOf("From:") == 0)
				{
					relCheck = "from";
					from = decodeString(line.substring(5));
				}
				else if(subject == "" && line.indexOf("Subject:") != -1)
				{
					relCheck = "subject";
					subject = decodeString(line.substring(8));
					trace(i, subject);
				}
				else if(reply == "" && line.indexOf("Return:") == 0)
				{
					relCheck = "reply";
					reply = decodeString(line.substring(7));
				}
				else if(to == "" && line.indexOf("To:") == 0)
				{
					relCheck = "to";
					to = decodeString(line.substring(3));
				}
				else if(cc == "" && line.indexOf("Cc:") == 0)
				{
					relCheck = "cc";
					cc = decodeString(line.substring(3));
				}
				else if(line.indexOf("=?") == -1)
				{
					relCheck = "";
				}
			}
			
		}
		
		private function decodeString($value:String):String
		{
			var str:String = DecodeMimeHeader.decode(StringUtil.trim($value));
			return str;
		}
		
	}
}